package com.daisuxia.web.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.back.utils.WebClient;
import com.daisuxia.constant.CollectionConstant;
import com.daisuxia.constant.Constant;
import com.daisuxia.constant.FuYouConstant;
import com.daisuxia.risk.service.IOutOrdersService;
import com.daisuxia.web.dao.IBorrowOrderDao;
import com.daisuxia.web.dao.IIndexDao;
import com.daisuxia.web.dao.IPaginationDao;
import com.daisuxia.web.dao.IRenewalRecordDao;
import com.daisuxia.web.dao.IRepaymentDao;
import com.daisuxia.web.dao.IRepaymentDetailDao;
import com.daisuxia.web.dao.IUserDao;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.OutOrders;
import com.daisuxia.web.pojo.Payment;
import com.daisuxia.web.pojo.RenewalRecord;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.RepaymentDetail;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserContacts;
import com.daisuxia.web.pojo.fuyou.MobilePaySend;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.HttpUtil;
import com.daisuxia.web.util.MapConvertCoreUtils;
import com.daisuxia.web.util.P2pUtils;
import com.daisuxia.web.util.PMD5Utils;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.SendSmsUtil;
import com.daisuxia.web.util.StringUtils;
import com.daisuxia.web.util.XmlUtil;
import com.fuiou.mpay.encrypt.DESCoderFUIOU;

import net.sf.json.JSONObject;
import redis.clients.jedis.JedisCluster;

@Service
public class RepaymentService implements IRepaymentService {

	private static Logger logger = Logger.getLogger(RepaymentService.class);
	@Autowired
	private IRepaymentDao repaymentDao;
	@Autowired
	private IRenewalRecordDao renewalRecordDao;
	@Autowired
	private IBorrowOrderDao borrowOrderDao;
	@Autowired
	private IRepaymentDetailDao repaymentDetailDao;
	@Autowired
	private IPaginationDao paginationDao;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IUserDao userDao;
	@Autowired
	private IIndexDao indexDao;
	@Autowired
	private IUserService userService;
	@Autowired
	private IUserContactsService userContactsService;
	@Autowired
	private IUserBankService userBankService;
	@Autowired
	private IOutOrdersService outOrdersService;
	@Autowired
	private IJsStepRecordService jsStepRecordService;
	@Autowired
	private IPushUserService pushUserService;
	@Autowired
	private IRepaymentDetailService repaymentDetailService;
	@Autowired
	private JedisCluster jedisCluster;
	@Autowired
	private SequenceManagerService sequenceManagerService;
	@Override
	public List<Repayment> findAll(HashMap<String, Object> params) {
		return null;
	}

	@Override
	public List<RepaymentDetail> findDetailsByRepId(Integer id) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("assetRepaymentId", id);
		return repaymentDetailDao.findParams(params);
	}

	@Override
	public Repayment findOneRepayment(Map<String, Object> params) {
		List<Repayment> repayments = repaymentDao.findParams(params);
		return null != repayments ? repayments.get(0) : null;
	}

	@Override
	public List<Map<String, Object>> findMyLoan(Map<String, Object> params) {
		return repaymentDao.findMyLoan(params);
	}

	@Override
	public Repayment selectByPrimaryKey(Integer id) {
		return repaymentDao.selectByPrimaryKey(id);
	}

	@Override
	public boolean deleteByPrimaryKey(Integer id) {
		return repaymentDao.deleteByPrimaryKey(id) > 0;
	}

	@Override
	public boolean insert(Repayment repayment) {
		return repaymentDao.insert(repayment) > 0;
	}

	@Override
	public boolean insertSelective(Repayment repayment) {
		return repaymentDao.insertSelective(repayment) > 0;
	}

	@Override
	public boolean updateByPrimaryKey(Repayment repayment) {
		return repaymentDao.updateByPrimaryKey(repayment) > 0;
	}

	@Override
	public boolean updateByPrimaryKeySelective(Repayment repayment) {
		return repaymentDao.updateByPrimaryKeySelective(repayment) > 0;
	}

	@Override
	public PageConfig<Repayment> findPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "Repayment");
		return paginationDao.findPage("findParams", "findParamsCount", params, "web");
	}

	@Override
	public List<Repayment> findParams(Map<String, Object> params) {
		return repaymentDao.findParams(params);
	}

	@Override
	public ServiceResult withhold(Repayment re, User user, int withholdType, Long money, String debitType) {
		ServiceResult serviceResult = new ServiceResult("-101", "扣款失败");
		try{
			String repayment_no = null;
			if(Repayment.TASK_WITHHOLD == withholdType && StringUtils.isNotBlank(re.getRepaymentNo())){
				repayment_no = re.getRepaymentNo();
			}
			if(StringUtils.isBlank(repayment_no)){
				Map<String,Object> map = P2PWithHold(re,  user, money);
				if (null!=map.get("errorcode")&&0==(Integer)map.get("errorcode")) {//已接收
					if (!"".equals(map.get("dataresult"))) {
						Date currentDate = new Date();
						//生成还款明细
						RepaymentDetail detail = new RepaymentDetail();
						detail.setUserId(re.getUserId());
						detail.setAssetRepaymentId(re.getId());
						detail.setTrueRepaymentMoney(money);
						if(null!=map.get("orderNo"))
						detail.setOrderId(map.get("orderNo").toString());
						detail.setRepaymentType(RepaymentDetail.TYPE_BANK_CARD_AUTO);
						detail.setRemark(OutOrders.ACT_DEBIT.equals(debitType) ? "催收代扣" : "用户主动代扣");
						detail.setStatus(RepaymentDetail.STATUS_WAIT);
						detail.setAssetOrderId(re.getAssetOrderId());
						detail.setCreatedAt(currentDate);
						repaymentDetailService.insertSelective(detail);
						serviceResult = new ServiceResult("100", "交易处理中");
					}
				}else {
					serviceResult = new ServiceResult(map.get("errorcode").toString(), map.get("errormsg").toString());
				}
			}
		}
		catch (Exception e){
			logger.error("withhold error repaymentId=" + re.getId(), e);
			serviceResult = new ServiceResult("-100", "代扣失败");
		}
		return serviceResult;
	}

	
	/**
	 * 由原来的访问支付路由改为 访问P2P接口，由P2P进行扣款
	 * @param string 
	 */
	private  Map<String, Object> P2PWithHold(Repayment re, User user,  Long money) {
		LinkedHashMap<String, String> mapApi = SysCacheUtils.getConfigParams(BackConfigParams.YANGYUE_MDL_API);
		String url = mapApi.get(BackConfigParams.MDL_POST_URL);
		String _client_ = mapApi.get(BackConfigParams.MDL_SYS_CLIENT);
		String key = mapApi.get(BackConfigParams.MDL_SYS_KEY);
		String _cmd_ = mapApi.get(BackConfigParams.MDL_LOAN_PAYMENT);
		String _deviceid_ = mapApi.get(BackConfigParams.MDL_SYS_DEVICEID);
		BorrowOrder bo = borrowOrderDao.selectByPrimaryKey(re.getAssetOrderId());
		Long remainderMoney = re.getRepaymentAmount() - re.getRepaymentedAmount();
		String callBackUrl = mapApi.get(BackConfigParams.OVERDUE_WITHHOLD_CALLBACK);
		Map<String, Object> map = new HashMap<>();
		//业务参数
		String orderNo = null;//本次代扣订单号 用于以后回调时候区别是哪笔代扣
		if(null!=re.getWithholdId())
			orderNo = re.getWithholdId();
		else
			orderNo = sequenceManagerService.getNewId()+"";
		Payment payment = new Payment();
		payment.setUser_apply_no(bo.getOutTradeNo());
		payment.setType("overdue");//逾期代扣
		payment.setRemainder_money(remainderMoney+"");//剩余应还金额(让p2p判断是否应该关闭该笔订单)
		payment.setMoney(money+"");//扣款金额
		payment.setUnique_mark(orderNo);
		payment.setPartial_money(String.valueOf(money));//部分还款金额(单位分)，整数 ，大于 100
		payment.setCall_back_url(callBackUrl);//部分还款时传，回调地址
		String pxh = MapConvertCoreUtils.createLinkString(MapConvertCoreUtils.paraFilter(MapConvertCoreUtils.object2Map(payment)));
		String sign = PMD5Utils.encodeByMD5(_client_ + "|" + key + "|" + _cmd_ + "|" + pxh);
		
		Map<String, Object> mm = new HashMap<String, Object>();
		mm = MapConvertCoreUtils.object2Map(payment);
		mm.put("_sign_", sign);
		mm.put("_cmd_", _cmd_);
		mm.put("_client_", _client_);
		mm.put("_deviceid_", _deviceid_);
		
		Map<String, String> w = MapConvertCoreUtils.object2MapString(mm);
		
		OutOrders outOrders = new OutOrders();
		String tablelastName = DateUtil.getDateFormat(new Date(), "yyyyMMdd");
		outOrders.setUserId(user.getId());
		outOrders.setOrderNo(orderNo);
		outOrders.setAssetOrderId(re.getId());
		outOrders.setOrderType(OutOrders.TYPE_P2P);
		outOrders.setAct(OutOrders.ACT_DEBIT);
		outOrders.setReqParams(JSONObject.fromObject(w).toString());
		outOrders.setStatus(OutOrders.STATUS_WAIT);
		outOrders.setTablelastName(tablelastName);
		outOrdersService.insertByTablelastName(outOrders);
		
		try {
			logger.info("催收代扣请求参数:"+w);
			String res = WebClient.getInstance().doPost(url, w);
			//{"errorcode":10023,"errormsg":"11111111","dataresult":"","servertime":1505457821}
			JSONObject json = JSONObject.fromObject(res);
			map = JSONObject.fromObject(json);
			logger.info("催收代扣p2p反回参数:"+map);
			if (null!=map&&null!=map.get("errorcode")&&0==(Integer)map.get("errorcode")) {//成功
				if (null!=map.get("dataresult")&&!"".equals(map.get("dataresult"))) {
					OutOrders upOrders = new OutOrders();
					upOrders.setId(outOrders.getId());
					upOrders.setReturnParams(json.toString());
					upOrders.setStatus(OutOrders.STATUS_SUC);
					outOrdersService.update(upOrders);
					map.put("orderNo", outOrders.getOrderNo());
				}
			}
			return map;
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
		
		return map;
	}
	
	
	@Override
	public void repay(Repayment re, RepaymentDetail detail) {
		BorrowOrder bo = new BorrowOrder();
		bo.setId(re.getAssetOrderId());
		Repayment copy = new Repayment();
		copy.setId(re.getId());
		copy.setRepaymentedAmount(re.getRepaymentedAmount() + detail.getTrueRepaymentMoney());

		User user = userDao.selectCollectionByUserId(re.getUserId());
		User userCopy = new User();
		userCopy.setId(user.getId());

		// 全部还清
		if (copy.getRepaymentedAmount() >= re.getRepaymentAmount()) {
			if (re.getLateDay() > 0) {
				copy.setStatus(BorrowOrder.STATUS_YQYHK);
				bo.setStatus(BorrowOrder.STATUS_YQYHK);
				// 逾期已还款 告知催收
				//collection(user, re, detail, Repayment.REPAY_COLLECTION);
				try {
					jedisCluster.set("REPAY_" + re.getId(), ""+re.getId());
					jedisCluster.del("OVERDUE_" + re.getId());
					logger.error("collection repay success YQYHK REPAY_" + re.getId() + " value=" + jedisCluster.get("REPAY_" + re.getId()) + " OVERDUE=" + jedisCluster.get("OVERDUE_" + re.getId()));
					if(StringUtils.isNotBlank(re.getWithholdId())){
						jedisCluster.set("WITHHOLD_" + re.getWithholdId(), re.getWithholdId());
						logger.error("collection repay success WITHHOLD_" + re.getWithholdId());
					}
				} catch (Exception e) {
					logger.error("collection repay error YQYHK repaymentId=" + re.getId(), e);
				}
			} else {
				copy.setStatus(BorrowOrder.STATUS_YHK);
				bo.setStatus(BorrowOrder.STATUS_YHK);
			}
			if (User.CUSTOMER_NEW.equals(user.getCustomerType())) {
				userCopy.setCustomerType(User.CUSTOMER_OLD);
			}
			// 全部还款-更新info_user_info borrow_status 状态为不可见
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("USER_ID", user.getId());
			map.put("BORROW_STATUS", "0");

			indexDao.updateInfoUserInfoBorrowStatus(map);

			copy.setRepaymentRealTime(null != detail.getCreatedAt() ? detail.getCreatedAt() : new Date());
			//通知p2p防止p2p重复扣款
			BorrowOrder borrow = borrowOrderService.findOneBorrow(re.getAssetOrderId());
			P2pUtils.finishOrder(borrow.getOutTradeNo(), System.currentTimeMillis());
		} else {
			if (re.getLateDay() > 0) {
				// 逾期部分还款 告知催收
//				collection(user, re, detail, Repayment.BREPAY_COLLECTION);
				try {
					jedisCluster.set("OVERDUE_" + re.getId(), ""+re.getId());
					logger.error("collection repay success OVERDUE_" + re.getId());
					if(StringUtils.isNotBlank(re.getWithholdId())){
						jedisCluster.set("WITHHOLD_" + re.getWithholdId(), re.getWithholdId());
						logger.error("collection repay success WITHHOLD_" + re.getId());
					}
				} catch (Exception e) {
					logger.error("collection repay error BFHK repaymentId=" + re.getId(), e);
				}
			}else{
				copy.setStatus(BorrowOrder.STATUS_BFHK);
				bo.setStatus(BorrowOrder.STATUS_BFHK);
			}
		}
		// 还款金额
		Long money = detail.getTrueRepaymentMoney();
		// 已付的逾期费 = 所有还款金额 - 借款金额 - 手续费
		Long payedOver = re.getRepaymentedAmount() - (re.getRepaymentInterest() + re.getRepaymentPrincipal());
		money = payedOver > 0 ? money - payedOver : money;
		if(money > 0){
			// 把用户可借额度加上
			if((Long.parseLong(user.getAmountAvailable() + money)>Long.parseLong(user.getAmountMax()))){//不能大于总额度
				userCopy.setAmountAvailable(user.getAmountMax());
			}else {
				userCopy.setAmountAvailable(String.valueOf(Long.parseLong(user.getAmountAvailable()) + money));
			}
			logger.error("用户额度变回成功userId=" + userCopy.getId() + ",amountAvailable=" + userCopy.getAmountAvailable());
		}
		else{
			logger.error("用户额度变回失败userId=" + userCopy.getId() + ",money=" + money + ",payedOver=" + payedOver + ",trueRepaymentMoney=" + detail.getTrueRepaymentMoney());
		}
		if(StringUtils.isNotBlank(userCopy.getCustomerType()) || StringUtils.isNotBlank(userCopy.getAmountAvailable())){
			userDao.updateAmountAvailableByUserId(userCopy);
			logger.error("用户额度保存成功userId=" + userCopy.getId() + ",amountAvailable=" + userCopy.getAmountAvailable());
		}
		else{
			logger.error("用户额度保存失败userId=" + userCopy.getId() + ",customerType=" + userCopy.getCustomerType() + ",amountAvailable=" + userCopy.getAmountAvailable());
		}
		if(null != bo.getStatus()){
			borrowOrderDao.updateByPrimaryKeySelective(bo);
		}
		repaymentDao.updateByPrimaryKeySelective(copy);
		
	}

	/**
	 * 续期
	 * 
	 * @param repayment
	 * @param record
	 * @return
	 */
	@Override
	public void renewal(Repayment repayment, RenewalRecord record) {
		if (null == repayment) {
			repayment = this.selectByPrimaryKey(record.getAssetRepaymentId());
		}
		// 更新续期为成功
		record.setStatus(RenewalRecord.STATUS_SUCC);
		renewalRecordDao.updateByPrimaryKeySelective(record);

		BorrowOrder borrowOrder = new BorrowOrder();
		borrowOrder.setId(repayment.getAssetOrderId());
		borrowOrder.setStatus(BorrowOrder.STATUS_HKZ);
		borrowOrderService.updateById(borrowOrder);

		Repayment re = new Repayment();
		// 如果申请续期成功
		re.setId(repayment.getId());
		re.setRepaymentAmount(repayment.getRepaymentAmount() - repayment.getPlanLateFee());
//		re.setPlanLateFee(repayment.getRepaymentAmount().intValue() - repayment.getPlanLateFee());
		re.setPlanLateFee(0);
		re.setTrueLateFee(0);
		// 还款日期 延后 （逾期天数+续期天数）
		re.setRepaymentTime(DateUtil.addDay(repayment.getRepaymentTime(), record.getRenewalDay()));
		re.setLateFeeStartTime(null);
		re.setInterestUpdateTime(null);
		re.setLateDay(0);
		re.setRenewalCount(repayment.getRenewalCount() + 1);
		re.setStatus(BorrowOrder.STATUS_HKZ);
		re.setCollection(Repayment.COLLECTION_NO);
		this.updateRenewalByPrimaryKey(re);

		// 如果是已逾期的续期（调用催收同步）
		if (repayment.getStatus().equals(BorrowOrder.STATUS_YYQ)) {
			try {
				jedisCluster.set("RENEWAL_" + re.getId(), ""+re.getId());
				logger.error("collection renewal success RENEWAL_" + re.getId());
			} catch (Exception e) {
				logger.error("collection renewal error repaymentId=" + re.getId(), e);
			}
		}
	}

	@Override
	public void updateRenewalByPrimaryKey(Repayment re) {
		repaymentDao.updateRenewalByPrimaryKey(re);
	}

	/**
	 * 催收调用
	 *
	 * @param u
	 *            用户信息
	 * @param re
	 *            还款信息
	 * @return
	 */
	@Override
	public Repayment collection(User u, Repayment re, RepaymentDetail detail, int collType) {
		logger.error("collection applying userId = " + u.getId() + " - repaymentId " + re.getId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		BorrowOrder bo = borrowOrderService.findOneBorrow(re.getAssetOrderId());

		List<Map> loanList = new ArrayList<Map>();

		Map<String, Object> loanMap = new HashMap<String, Object>();

		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("userId", u.getId());
		List<UserContacts> userContacts = userContactsService.selectUserContacts(params);
		// 应还本金
		int receivablePrinciple = re.getRepaymentAmount().intValue() - re.getPlanLateFee();
		// 实收的利息 = 已还金额 - 应还本金
		int realPenlty = re.getRepaymentedAmount().intValue() - receivablePrinciple;

		if(collType == Repayment.OVERDUE_COLLECTION){
			// 紧急联系人
			List<Map> mmanUserRelas = new ArrayList<Map>();
			Map<String, String> mmanUserRela = new HashMap<String, String>();
			mmanUserRela.put("id", "");
			mmanUserRela.put("userId", u.getId());
			mmanUserRela.put("contactsKey", "1");
			mmanUserRela.put("relaKey", u.getFristContactRelation());
			mmanUserRela.put("infoName", u.getFirstContactName());
			mmanUserRela.put("infoValue", u.getFirstContactPhone());
			mmanUserRela.put("contactsFlag", "1");
			mmanUserRelas.add(mmanUserRela);

			mmanUserRela = new HashMap<String, String>();
			mmanUserRela.put("id", "");
			mmanUserRela.put("userId", u.getId());
			mmanUserRela.put("contactsKey", "2");
			mmanUserRela.put("relaKey", u.getSecondContactRelation());
			mmanUserRela.put("infoName", u.getSecondContactName());
			mmanUserRela.put("infoValue", u.getSecondContactPhone());
			mmanUserRela.put("contactsFlag", "1");
			mmanUserRelas.add(mmanUserRela);

			for (UserContacts contacts : userContacts) {
				mmanUserRela = new HashMap<String, String>();
				mmanUserRela.put("id", contacts.getId());
				mmanUserRela.put("userId", u.getId());
				mmanUserRela.put("contactsKey", "2");
				mmanUserRela.put("infoName", contacts.getContactName());
				mmanUserRela.put("infoValue", contacts.getContactPhone());
				mmanUserRelas.add(mmanUserRela);
			}

			loanMap.put("mmanUserInfo", u);
			loanMap.put("mmanUserRelas", mmanUserRelas);


			// 银行卡信息
			Map<String, Object> bankCard = new HashMap<String, Object>();
			params.put("limit", 1);
			List<UserCardInfo> userCardInfos = userBankService.findUserCardByUserId(params);
			if (null != userCardInfos && userCardInfos.size() > 0) {
				UserCardInfo cardInfo = userCardInfos.get(0);
				bankCard.put("id", cardInfo.getId());
				bankCard.put("userId", cardInfo.getUserId());
				bankCard.put("bankCard", cardInfo.getCard_no());
				bankCard.put("depositBank", cardInfo.getBankName());
				bankCard.put("mobile", cardInfo.getPhone());
			}

			loanMap.put("bankCard", bankCard);

			// 还款详情
			List<Map> creditLoanPayDetails = new ArrayList<Map>();
			List<RepaymentDetail> rds = this.findDetailsByRepId(re.getId());
			Map<String, Object> creditLoanPayDetail;
			for (RepaymentDetail rd : rds) {
				creditLoanPayDetail = new HashMap<String, Object>();
				creditLoanPayDetail.put("id", rd.getId());
				Map<String, Object> temp = new HashMap<String, Object>();
				temp.put("id", re.getId());
				creditLoanPayDetail.put("payId", temp);

				if(realPenlty <= 0){
					creditLoanPayDetail.put("realMoney", rd.getTrueRepaymentMoney() / 100.00);
					creditLoanPayDetail.put("realPenlty", 0);

					creditLoanPayDetail.put("realPrinciple", (receivablePrinciple - re.getRepaymentedAmount()) / 100.00);
					creditLoanPayDetail.put("realInterest", re.getPlanLateFee() / 100.00);
				}
				else{
					creditLoanPayDetail.put("realMoney", (rd.getTrueRepaymentMoney() - realPenlty)  / 100.00);
					creditLoanPayDetail.put("realPenlty", realPenlty / 100.00);

					creditLoanPayDetail.put("realPrinciple", 0);
					creditLoanPayDetail.put("realInterest", (re.getRepaymentAmount() - re.getRepaymentedAmount()) / 100.00);
				}
				creditLoanPayDetail.put("returnType", rd.getRepaymentType());
				creditLoanPayDetail.put("remark", rd.getRemark());

				creditLoanPayDetails.add(creditLoanPayDetail);
			}

			loanMap.put("creditLoanPayDetails", creditLoanPayDetails);
		}

		if(collType == Repayment.REPAY_COLLECTION || collType == Repayment.OVERDUE_COLLECTION || collType == Repayment.RENEWAL_COLLECTION){

			// 借款信息
			Map<String, Object> mmanUserLoan = new HashMap<String, Object>();
			mmanUserLoan.put("id", bo.getId());
			mmanUserLoan.put("userId", u.getId());
			mmanUserLoan.put("loanPyId", bo.getOutTradeNo());
			mmanUserLoan.put("loanMoney", bo.getMoneyAmount() / 100.00);
			mmanUserLoan.put("loanRate", bo.getApr());
			mmanUserLoan.put("loanPenalty", re.getPlanLateFee() / 100.00);
			mmanUserLoan.put("loanPenaltyRate", bo.getLateFeeApr());
			mmanUserLoan.put("loanStartTime", sdf.format(re.getCreditRepaymentTime()));
			mmanUserLoan.put("loanEndTime", sdf.format(re.getRepaymentTime()));
			mmanUserLoan.put("loanStatus", re.getStatus());

			loanMap.put("mmanUserLoan", mmanUserLoan);
		}

		// 还款信息
		Map<String, Object> creditLoanPay = new HashMap<String, Object>();
		creditLoanPay.put("id", re.getId());
		Map<String, Object> temp = new HashMap<String, Object>();
		temp.put("id", bo.getId());

		creditLoanPay.put("loanId", temp);
		creditLoanPay.put("receivableStartdate", sdf.format(re.getCreditRepaymentTime()));
		creditLoanPay.put("receivableDate", sdf.format(re.getRepaymentTime()));
		creditLoanPay.put("receivableMoney", re.getRepaymentAmount() / 100.00);
//		creditLoanPay.put("receivablePrinciple", receivablePrinciple / 100.00);
//		creditLoanPay.put("receivableInterest", re.getPlanLateFee() / 100.00);
		creditLoanPay.put("realMoney", re.getRepaymentedAmount() / 100.00);
		if(realPenlty <= 0){
			creditLoanPay.put("receivablePrinciple", (receivablePrinciple - re.getRepaymentedAmount()) / 100.00);
			creditLoanPay.put("receivableInterest", re.getPlanLateFee() / 100.00);
			creditLoanPay.put("realgetPrinciple", re.getRepaymentedAmount() / 100.00);
			creditLoanPay.put("realgetInterest", 0);
		}
		else{
			creditLoanPay.put("receivablePrinciple", 0);
			creditLoanPay.put("receivableInterest", (re.getRepaymentAmount() - re.getRepaymentedAmount()) / 100.00);
			creditLoanPay.put("realgetPrinciple", (re.getRepaymentedAmount().intValue() - realPenlty) / 100.00);
			creditLoanPay.put("realgetInterest", realPenlty / 100.00);
		}

		creditLoanPay.put("status", re.getStatus());



		loanMap.put("creditLoanPay", creditLoanPay);

		if(collType == Repayment.BREPAY_COLLECTION || collType == Repayment.REPAY_COLLECTION){
			// 还款详情
			List<Map> creditLoanPayDetails = new ArrayList<Map>();
			Map<String, Object> creditLoanPayDetail;
			creditLoanPayDetail = new HashMap<String, Object>();
			creditLoanPayDetail.put("id", detail.getId());
			temp = new HashMap<String, Object>();
			temp.put("id", re.getId());
			creditLoanPayDetail.put("payId", temp);

			if(realPenlty <= 0){
				creditLoanPayDetail.put("realMoney", detail.getTrueRepaymentMoney() / 100.00);
				creditLoanPayDetail.put("realPenlty", 0);

				creditLoanPayDetail.put("realPrinciple", (receivablePrinciple - re.getRepaymentedAmount()) / 100.00);
				creditLoanPayDetail.put("realInterest", re.getPlanLateFee() / 100.00);
			}
			else{
				creditLoanPayDetail.put("realMoney", (detail.getTrueRepaymentMoney() - realPenlty)  / 100.00);
				creditLoanPayDetail.put("realPenlty", realPenlty / 100.00);

				creditLoanPayDetail.put("realPrinciple", 0);
				creditLoanPayDetail.put("realInterest", (re.getRepaymentAmount() - re.getRepaymentedAmount()) / 100.00);
			}
			creditLoanPayDetail.put("returnType", detail.getRepaymentType());
			creditLoanPayDetail.put("remark", detail.getRemark());

			creditLoanPayDetails.add(creditLoanPayDetail);

			loanMap.put("creditLoanPayDetails", creditLoanPayDetails);
		}

		loanList.add(loanMap);

		Map<String, Object> collectionRelevantJson = new HashMap<String, Object>();
		collectionRelevantJson.put("collectionRelevantJson", loanList);

		// 设置参数 可设置多个
		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair("collectionRelevantJson", JSONObject.fromObject(collectionRelevantJson).toString()));
		try {
			String result = HttpUtil.getInstance().post(CollectionConstant.getCollectionPath(), postParams);
			JSONObject obj = JSONObject.fromObject(result);
			if (obj.getString("code").equals("0")) {
				re.setCollection(Repayment.COLLECTION_YES);
			}
		} catch (Exception e) {
			logger.error("collection error", e);
		}
		return re ;
	}

	@Override
	public List<Repayment> findAllByBorrowId(Integer borrowId) {
		return repaymentDao.findAllByBorrowId(borrowId);
	}

	@Override
	public Map<String, Object> findBorrowLoanTerm(Integer borrowId) {
		return repaymentDao.findBorrowLoanTerm(borrowId);
	}

	@Override
	public boolean insertByBorrorOrder(BorrowOrder borrowOrder) {
		Date fkDate = borrowOrder.getLoanTime();
		Repayment repayment = new Repayment();
		repayment.setUserId(borrowOrder.getUserId());
		repayment.setAssetOrderId(borrowOrder.getId());
		repayment.setRepaymentAmount(Long.valueOf(borrowOrder.getMoneyAmount()));
		repayment.setLateFeeApr(borrowOrder.getLateFeeApr());
		repayment.setRepaymentedAmount(0L);
		repayment.setRepaymentPrincipal(Long.valueOf(borrowOrder.getIntoMoney()));
		repayment.setRepaymentInterest(Long.valueOf(borrowOrder.getLoanInterests()));

		repayment.setRepaymentTime(DateUtil.addDay(fkDate, borrowOrder.getLoanTerm()));// 放款时间加上借款期限
		repayment.setCreatedAt(fkDate);
		repayment.setUpdatedAt(fkDate);
		repayment.setStatus(borrowOrder.getStatus());
		repaymentDao.insertSelective(repayment);
		User user = userDao.searchByUserid(borrowOrder.getUserId());
		SendSmsUtil.sendSmsDiyCL(user.getUserPhone(), "你收到贷速侠打款" + borrowOrder.getIntoMoney() / 100 + "元,预计很快到账，请注意查收！");
//
//		//借款成功
//		try{
//			//生成大抽奖的抽奖码
//	        HashMap<String,String> stepMap=new HashMap<String,String>();
//	        stepMap.put("userPhone", user.getUserPhone());
//	        stepMap.put("awardType", "BORROW");
//	        logger.info("addUserStep   BORROW  请求参数："+stepMap.toString());
//	        ServiceResult serviceResult=   jsStepRecordService.addUserStep(stepMap);
//				logger.info("addUserStep 抽奖返回>>>："+serviceResult.getCode()+":"+serviceResult.getMsg());
//		}catch (Exception e) {
//			logger.error("addUserStep error BORROW",e);
//		}
		
		
		return true;
	}

	/**
	 * 富友支付封装
	 * 
	 * @return
	 */
	@Override
	public Map<String, String> payAction(User user, UserCardInfo info, MobilePaySend paySend, Long money, String act, String orderNo) {
		Map<String, String> params = null;
		paySend.setMCHNTCD(FuYouConstant.getMchntcd());
		paySend.setTYPE(FuYouConstant.TYPE);
		paySend.setVERSION(FuYouConstant.VERSION);
		paySend.setLOGOTP(FuYouConstant.LOGOTP);
		paySend.setMCHNTORDERID(orderNo);
		paySend.setUSERID(user.getId());
		paySend.setAMT(String.valueOf(money));
		paySend.setBANKCARD(info.getCard_no());
		paySend.setNAME(user.getRealname());
		paySend.setIDTYPE(FuYouConstant.IDTYPE);
		paySend.setIDNO(user.getIdNumber());
		paySend.setSIGNTP(FuYouConstant.SIGNTP);
		paySend.setSIGN(paySend.toSign());
		String reply_mesg = null;
		try {
			params = new HashMap<String, String>();
			reply_mesg = XmlUtil.toXml(MobilePaySend.class, paySend);
			params.put("FM", DESCoderFUIOU.desEncrypt(reply_mesg, DESCoderFUIOU.getKeyLength8(FuYouConstant.getKey())));
			params.put("ENCTP", FuYouConstant.ENCTP_YES);
			params.put("VERSION", FuYouConstant.VERSION);
			params.put("MCHNTCD", FuYouConstant.getMchntcd());
			params.put("ORDERNO", orderNo);

			OutOrders outOrders = new OutOrders();
			outOrders.setUserId(user.getId());
			outOrders.setOrderType(OutOrders.TYPE_FUYOU);
			outOrders.setOrderNo(orderNo);
			outOrders.setAct(act);
			outOrders.setReqParams(params.toString());
			outOrdersService.insert(outOrders);
		} catch (Exception e) {
			logger.error("fuyou payAction error", e);
		}
		return params;
	}

}
